package com.ysqcould.content.service.impl;


import cn.hutool.core.util.ObjectUtil;
import com.alibaba.fastjson.JSONObject;
import com.ysqcould.common.utils.DateUtils;
import com.ysqcould.common.utils.http.HttpUtils;
import com.ysqcould.common.utils.httpClient.HttpClientUtil;
import com.ysqcould.common.utils.uuid.ArrayUtil;
import com.ysqcould.content.domain.Press;
import com.ysqcould.content.domain.PressType;
import com.ysqcould.content.domain.SecondType;
import com.ysqcould.content.domain.bo.PressBo;
import com.ysqcould.content.mapper.PressMapper;
import com.ysqcould.content.mapper.PressTypeMapper;
import com.ysqcould.content.mapper.SecondTypeMapper;
import com.ysqcould.content.service.IPressService;
import com.ysqcould.system.mapper.DictMapper;
import lombok.extern.slf4j.Slf4j;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.jsoup.select.Elements;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.*;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import static com.ysqcould.common.oss.OssClientUtil.uploadUrlImage;
import static com.ysqcould.common.utils.SecurityUtils.getUserId;

/**
 * 新闻Service业务层处理
 * 
 * @author ruoyi
 * @date 2022-06-28
 */
@Slf4j
@Service
public class PressServiceImpl implements IPressService
{
    @Resource
    private PressMapper pressMapper;

    @Resource
    private PressTypeMapper pressTypeMapper;

    @Resource
    private SecondTypeMapper secondTypeMapper;

    @Resource
    private DictMapper dictMapper;

    /**
     * 查询新闻
     * 
     * @param id 新闻主键
     * @return 新闻
     */
    @Override
    public Press selectPressById(Long id)
    {
        final Long userId = getUserId();
        final Press press = pressMapper.selectPressById(id);
        if (ObjectUtil.isNotEmpty(press.getType())){
            final String[] split = press.getType().split(",");
            final int[] ints = Arrays.stream(split).mapToInt(Integer::parseInt).toArray();
            press.setOneType(ints);
        }
        if (ObjectUtil.isNotEmpty(press.getTypeTwo())){
             press.setTwoType(Arrays.stream(press.getTypeTwo().split(",")).mapToInt(Integer::parseInt).toArray());
        }
        return press;
    }

    /**
     * 查询新闻列表
     * 
     * @param press 新闻
     * @return 新闻
     */
    @Override
    public List<Press> selectPressList(Press press){
        List<Press> presses = pressMapper.selectPressList(press);
        presses.forEach(p->{
            String[]strings=p.getPcUrl().split(";");
            p.setPcUrl(strings[0]);
        });
        return presses;
    }

    /**
     * 新增新闻
     * 
     * @param press 新闻
     * @return 结果
     */
    @Override
    public int insertPress(Press press)
    {
        final Long userId = getUserId();
        press.setCreateTime(DateUtils.getNowDate());
        final String time = press.getTime();
        final String type = ArrayUtil.getStr(press.getOneType());
        final String typeTwo = ArrayUtil.getStr(press.getTwoType());
        press.setType(type);
        press.setTypeTwo(typeTwo);
        final Date date = DateUtils.parseDate(time);
        press.setStatus(0L);
        press.setReleaseTime(date);
        press.setAsId(userId);
        return pressMapper.insertPress(press);
    }

    /**
     * 修改新闻
     * 
     * @param press 新闻
     * @return 结果
     */
    @Override
    public int updatePress(Press press)
    {
        press.setUpdateTime(DateUtils.getNowDate());
        return pressMapper.updatePress(press);
    }

    /**
     * 批量删除新闻
     * 
     * @param ids 需要删除的新闻主键
     * @return 结果
     */
    @Override
    public int deletePressByIds(Long[] ids)
    {
        return pressMapper.deletePressByIds(ids);
    }

    /**
     * 删除新闻信息
     * 
     * @param id 新闻主键
     * @return 结果
     */
    @Override
    public int deletePressById(Long id)
    {
        return pressMapper.deletePressById(id);
    }

    @Override
    public List<String> getUrlList(String body) {
        List<String>list=new ArrayList<>();
         String str = body.replace("amp;amp;", "");
        Pattern p = Pattern.compile("[a-zA-z]+://[^\\\\;||^\\s]*");
         Matcher m = p.matcher(str);
        System.out.println(str);
        while (m.find()){
            if(m.group().contains("http://mp.weixin.qq.com/s")||m.group().contains("https://mp.weixin.qq.com/s")){
                boolean u = m.group().contains("#wechat_redirect");
                if (u){
                    String url  = m.group().substring(0,m.group().indexOf("#wechat_redirect"))+"#wechat_redirect";
                    list.add(url);
                    System.out.println(String.format("1: 文章内容图片地址-》%s",url));
                }}
        }
        System.out.println(list);
        return list;
    }



    @Override
    public List<JSONObject> getVauleList(List<String> urlList,String cookie) {
        List<JSONObject> valuesList=new ArrayList<>();
        Map<String,String> map=new HashMap<>();
        urlList.forEach(p->{
            p.replace("oup","");
            map.put("Cookie",cookie);
            map.put("User-Agent","Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/81.0.4044.138 Safari/537.36 NetType/WIFI MicroMessenger/7.0.20.1781(0x6700143B");
            String body = HttpClientUtil.get(p, map);
            Pattern compile = Pattern.compile(" var uin ([^=]+)$/");
             Matcher m = compile.matcher(body);
             if (m.find()){
                 System.out.println(m.group());
             }
        });
        return null;
    }

    /**
     * 查询二级数据
     * @param val
     * @return
     */
    @Override
    public List<SecondType> selectPressSecondType(long val) {
        System.out.println("获取的val"+val);
        final List<SecondType>  secondTypes= secondTypeMapper.selectSecondTypeAllList(val);
        return secondTypes;
    }

    /**
     * 获取新闻类文章一级分类
     * @param id 用户登录id
     * @return
     */
    @Override
    public List<PressType> getType(Long id) {
        Long asId=null;
        if (id!=1){
            asId=id;
        }
        List<PressType> pressTypes = pressTypeMapper.selectTypeList(asId);
        return pressTypes;
    }

    @Override
    public Press getContent(PressBo bo) {
        Press press=new Press();
        final String s = HttpUtils.sendGet(bo.getUrl());
        final Document doc = Jsoup.parse(s);
        /**文章内容**/
        final String content = doc.getElementById("js_content").html();
        /**文章标题**/
        final String title = doc.select("meta[property=\"twitter:title\"]").attr("content");
        /**文章标签**/
        final String tag = doc.select("meta[property=\"og:description\"]").attr("content");
        /**文章封面**/
        final String coverUrl = doc.select("meta[property=\"twitter:image\"]").attr("content");
        /**已上传文章封面**/
        final String urlImage = uploadUrlImage(coverUrl);
        final Elements img = doc.select("img");
        List<String>list=new ArrayList<>();
        Map<String,String>map=new HashMap<>();
        for (Element element : img) {
            final String url = element.attr("data-src");
            if (ObjectUtil.isNotEmpty(url)){
                final String image = uploadUrlImage(url);
                map.put(url,image);
            }

        }
        StringBuffer replaceContent=null;
        if (ObjectUtil.isNotEmpty(map)){
            final Iterator<Map.Entry<String, String>> it = map.entrySet().iterator();
             while (it.hasNext()){
                 final Map.Entry<String, String> entry = it.next();
                 replaceContent = ObjectUtil.isEmpty(replaceContent) ? new StringBuffer(content):replaceContent;
                 replaceContent = new StringBuffer(ObjectUtil.isEmpty(replaceContent)?"":replaceContent.toString().replace(entry.getKey(), (entry.getValue())));
             }
            final String replace = replaceContent.toString().replace("data-src", "src");
            press.setPcUrl(urlImage);
            press.setContent(replace);
            press.setTag(tag);
            press.setName(title);
        }
        return press;
    }

    /**
     * 下架文章
     * @param id
     * @return
     */
    @Override
    public int changStatus(Long id) {
        final Press press = pressMapper.selectPressById(id);
        press.setStatus(2L);
        return pressMapper.updatePress(press);
    }



}
